package com.xlf.service.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.core.exception.ServiceException;
import com.xlf.common.core.util.StringUtils;
import com.xlf.service.blog.domain.Article;
import com.xlf.service.blog.domain.Type;
import com.xlf.service.blog.mapper.ArticleMapper;
import com.xlf.service.blog.service.TypeService;
import com.xlf.service.blog.mapper.TypeMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
* @author 小新
* @description 针对表【t_type】的数据库操作Service实现
* @createDate 2023-07-08 15:51:57
*/
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type>
    implements TypeService{

    @Resource
    TypeMapper typeMapper;

    @Resource
    ArticleMapper articleMapper;



    @Override
    public Boolean deleteTypeByIds(List<Long> ids) {
        for (Long id : ids)
        {
            if (getArticleNum(id) > 0)
            {
                throw new ServiceException("分类下存在博客！不可删除");
            }
        }
        return removeByIds(ids);
    }

    @Override
    public List<Type> getList(Type type) {
        List<Type> types = Optional.ofNullable(list(new LambdaQueryWrapper<Type>().setEntity(type)
                        .like(StringUtils.isNotEmpty(type.getSearchValue()), Type::getName, type.getSearchValue())))
                .orElse(new ArrayList<>());
        types.forEach(item -> item.setArticleNum(getArticleNum(item.getId())));
        return types;
    }

    private int getArticleNum(Long id) {
        return articleMapper.selectCount(new LambdaQueryWrapper<Article>()
                .eq(Article::getTypeId, id)
                .eq(Article::getStatus, com.xlf.common.core.constant.Constants.NORMAL)).intValue();
    }
}




